<?php 
namespace Api\Model;

class UserCouponModel extends BaseModel{

	/**
	 * 获取用户可用优惠券
	 * @param 	int 	$user_id
	 * @param 	float 	$money
	 * @return 	array
	 */
	public function visiableCoupon($user_id,$money,$goods_id = 0){
		$valid_coupon = $this->validCoupon($user_id,$money,$goods_id);
		if($valid_coupon){
			$freeze_coupon = $this->freezeCoupon($user_id);
			$user_coupon_id = array();
			if($freeze_coupon){
				foreach ($freeze_coupon as $key => $value) {
					$temp = explode(',',$value['user_coupon_id']);
					$user_coupon_id = array_merge($user_coupon_id,$temp);
				}
			}
			if($user_coupon_id){
				foreach ($valid_coupon as $key => &$value) {
					if(in_array($value['id'],$user_coupon_id)){
						unset($valid_coupon[$key]);
					}
				}
			}
			$valid_coupon = array_values($valid_coupon);
		}
		return $valid_coupon?:array();
	}

	/**
	 * 获取用户未使用未过期的优惠券
	 * @param 	int 	$user_id
	 * @param   int 	$type    
	 * @return  array
	 */
	public function validCoupon($user_id,$money,$goods_id = 0){
		$Obj = D('Member');
        $model = 'UserCoupon';
        $where = "used_time = 0 AND expired >".time();
        if($goods_id){
        	$where .= ' AND ((type = 1 AND full_money < '.$money. ') or (type =2 AND goods_id = '.$goods_id.') or (type=3))';
        }else{
        	$where .= ' AND ((type = 1 AND full_money < '.$money. ') or (type=3))';
        }
        $fields = 'id,name,type,full_money,money';
        $Obj->relation($user_id,$model,$where,$fields);
        return $Obj->relation($user_id,$model,$where,$fields);
	}

	/**
	 * 获取用户下单未支付的优惠券id
	 * @param 	int 	$user_id
	 * @param 	int 	$shop_id
	 * @param   int 	$type    
	 * @return  array
	 */
	public function freezeCoupon($user_id){
		$Obj = D('Member');
        $model = 'Order';
        $where = 'status <= 2 AND coupon_money > 0';
        $fields = 'user_coupon_id';
        return $Obj->relation($user_id,$model,$where,$fields);
	}

}